package com.ctgu.demo04.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.demo04.entity.StocksEntity;
import com.ctgu.demo04.service.StocksService;
import com.ctgu.demo04.mapper.StocksMapper;
import com.ctgu.demo04.utils.ApiResult;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @author Alex2
* @description 针对表【t_stocks】的数据库操作Service实现
* @createDate 2025-03-12 11:47:21
*/
@Service
public class StocksServiceImpl extends ServiceImpl<StocksMapper, StocksEntity>
    implements StocksService {

    /**
     * @Author: Alex
     * @Description: 插入库存
     */
    @Override
    public ApiResult insertStock(String name, Integer stock) {
        StocksEntity stocks = lambdaQuery().eq(StocksEntity::getName, name).one();
        if (stocks != null) {
            return ApiResult.error("该库存已存在，插入失败");
        }
        StocksEntity stocksEntity = new StocksEntity(null, name, stock);
        boolean save = save(stocksEntity);
        if (!save) {
            return ApiResult.error("插入失败");
        } else {
            return ApiResult.success("插入成功");
        }
    }

    /**
     * @Author: Alex
     * @Description: 共享锁实现悲观锁
     */
    @Transactional
    @Override
    public ApiResult fetchVoucherByShareLock(Integer id) {
        StocksEntity stocks = baseMapper.selectStockWithShareLock(id); // 使用共享锁
        if (stocks == null || stocks.getStock() <= 0) {
            return ApiResult.error("库存不足");
        }
        boolean update = lambdaUpdate()
                .eq(StocksEntity::getId, id)
                .setSql("stock = stock - 1")
                .update();
        if (!update) {
            return ApiResult.error("库存不足");
        }
        return ApiResult.success("更新成功");
    }

    /**
     * @Author: Alex
     * @Description: 排他锁实现悲观锁
     */
    @Transactional
    @Override
    public ApiResult fetchVoucherByForUpdate(Integer id) {
        StocksEntity stocks = baseMapper.selectStockForUpdate(id); // 使用排他锁
        if (stocks == null || stocks.getStock() <= 0) {
            return ApiResult.error("库存不足");
        }
        boolean update = lambdaUpdate().eq(StocksEntity::getId, id).setSql("stock = stock - 1").update();
        if (!update) {
            return ApiResult.error("库存不足");
        }
        return ApiResult.success("更新成功");
    }
}